package com.zjmcollege.hotpot.controller;

import com.alibaba.fastjson.JSON;
import com.zjmcollege.hotpot.model.MsgModel;
import com.zjmcollege.hotpot.util.WebsocketUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author zpym
 * @CopyRight (C) http://www.iengoo.com
 * @brief
 * @email 122162005@qq.com
 * @date 2019-11-13 10:42
 */
@ServerEndpoint(value = "/ws")
@Component
@Slf4j
public class ChatServerEndpoint {
    private static final int USER_OPEN = 1;     // 用户连接
    public static final int USER_SEND_MSG = 2;  // 用户发送消息
    private static final int USER_CLOSE = 3;    // 用户断开连接

    private static final AtomicInteger ONLINE_COUNT = new AtomicInteger(0);
    // concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<Session> SOCKET_SESSION_SET
            = new CopyOnWriteArraySet<Session>();

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        SOCKET_SESSION_SET.add(session);
        int cnt = ONLINE_COUNT.incrementAndGet(); // 在线数加1
        log.info("有连接加入，当前连接数为：{}", cnt);
        openOrCloseNotice(session, USER_OPEN);
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {
        SOCKET_SESSION_SET.remove(session);
        int cnt = ONLINE_COUNT.decrementAndGet();
        log.info("有连接关闭，当前连接数为：{}", cnt);

        openOrCloseNotice(session, USER_CLOSE);
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message
     *            客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("来自客户端的消息：{}",message);

        String host = WebsocketUtil.host(session);

        HashMap<Object, Object> result = new HashMap<>();


        result.put("type", USER_SEND_MSG);
        MsgModel mm = ChatController.userInfos.get(host);
        mm.setMsg(JSON.parseObject(message, MsgModel.class).getMsg());
        result.put("content", mm);

//        SendMessage(session, JSON.toJSONString(result));
        try {
            BroadCastInfo(JSON.toJSONString(result));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 出现错误
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误：{}，Session ID： {}",error.getMessage(),session.getId());
        error.printStackTrace();
    }

    /**
     * 发送消息，实践表明，每次浏览器刷新，session会发生变化。
     * @param session
     * @param message
     */
    public static void SendMessage(Session session, String message) {
        try {
            session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            log.error("发送消息出错：{}", e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 群发消息
     * @param message
     * @throws IOException
     */
    public static void BroadCastInfo(String message) throws IOException {
        for (Session session : SOCKET_SESSION_SET) {
            if(session.isOpen()){
                SendMessage(session, message);
            }
        }
    }

    /**
     * 指定Session发送消息
     * @param sessionId
     * @param message
     * @throws IOException
     */
    public static void SendMessage(String sessionId,String message) throws IOException {
        Session session = null;
        for (Session s : SOCKET_SESSION_SET) {
            if(s.getId().equals(sessionId)){
                session = s;
                break;
            }
        }
        if(session != null){
            SendMessage(session, message);
        }
        else{
            log.warn("没有找到你指定ID的会话：{}",sessionId);
        }
    }

    /**
     * 上线线通知
     * @param session
     * @param type 通知类型
     */
    public static void openOrCloseNotice(Session session, int type) {
        String host = WebsocketUtil.host(session);

        try {
            HashMap<Object, Object> result = new HashMap<>();
            result.put("type", type);
            result.put("content", new MsgModel(ChatController.userInfos.get(host).getNickname(), host));
            /**
             * {
             *      type:1,
             *      msg: {nickname: "张三", ip: "122.111.111.1", avatar: "#"}
             * }
             */
            BroadCastInfo(JSON.toJSONString(result));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}